package net.anquankong.websec.argus;

import java.io.*;
import java.net.*;
import java.util.*;

import com.gargoylesoftware.htmlunit.*;
import com.gargoylesoftware.htmlunit.html.*;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class ServerListener {
	private static int listeningPort_;
	private static int maxThreads_;
	private static String tmpFolder_ = "";

	private static ServerSocket serverSocket_;

	private static Log log_ = LogFactory.getLog(ServerListener.class);

	/**
	 * Read properties from argusServer.properties file
	 * 
	 * @throws Exception
	 */
	private static void readProperties() throws Exception {
		Properties properties = new Properties();
		FileInputStream is = new FileInputStream("argusServer.properties");
		properties.load(is);

		listeningPort_ = Integer.valueOf(properties
				.getProperty("listeningPort"));
		log_.debug("Listening Port = " + Integer.toString(listeningPort_));
		maxThreads_ = Integer.valueOf(properties.getProperty("maxThreads"));
		log_.debug("Max Threads = " + Integer.toString(maxThreads_));
		
		tmpFolder_ = properties.getProperty("tmpFolder");
		if (tmpFolder_.charAt(tmpFolder_.length() - 1) != '\\') {
			tmpFolder_ += "\\"; 
		}
		log_.debug("Temp Folder = " + tmpFolder_);
	}

	/**
	 * Main
	 * 
	 * @param args
	 */
	public static void main(String[] args) {
		// Read properties
		try {
			readProperties();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return;
		}

		// Generate a WebClient instance, to load all the required classes and
		// initialize global objects
		WebClient globalWebClient = new WebClient();

		// Create server socket
		try {
			serverSocket_ = new ServerSocket(listeningPort_);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return;
		}

		int threadId = 0;

		while (true) {
			try {
				Socket clientSocket = serverSocket_.accept();
				ClientControlServiceThread controlThread = new ClientControlServiceThread(
						clientSocket, threadId, tmpFolder_);
				controlThread.start();

				if (threadId < Integer.MAX_VALUE) {
					threadId++;
				} else {
					threadId = 0;
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return;
			}
		}
	}
}
